/*
    在线翻译客户端: 利用muduo库快速搭建一个翻译客户端
*/
#include <iostream>
#include <string>
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"
#include "muduo/net/TcpConnection.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"


class TranslateClient
{
public:
    TranslateClient(int port, const std::string& ip = "127.0.0.1") :
        _base_loop_ptr(_loop_thread.startLoop()),
        _client(_base_loop_ptr, muduo::net::InetAddress(ip, port) ,"TranslateClient"),
        _downlatch(1)
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();
        _downlatch.wait();
    }

    void send(const std::string& msg)
    {
        if(_conn)
            _conn->send(msg);
    }

private:
    // 连接建立和断开时的回调
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected())
        {
            _conn = conn;
            _downlatch.countDown();
        }
        else
        {
            _conn.reset();
        }
    }

    
    // 接收到消息时的回调
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp time)
    {
        std::string msg = buf->retrieveAllAsString();
        std::cout << "Received: " << msg << std::endl;
    }

private:
    muduo::net::EventLoopThread _loop_thread;
    muduo::net::EventLoop* _base_loop_ptr;
    muduo::net::TcpClient _client;
    muduo::CountDownLatch _downlatch;
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    TranslateClient client(8080);
    client.connect();
    while(1)
    {
        std::string msg  = "";
        getline(std::cin, msg);
        client.send(msg);
    }
    return 0;
}